<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
            <el-input placeholder="请输入查询字段" v-model="getUserListParams.query" clearable @clear="getUserList" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="isVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" border stripe >
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column label="用户名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)" active-color="#0c7ace" inactive-color="#e7e3eb">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" @click="distrubuteRoles(scope.row)" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="getUserListParams.pagenum" :page-sizes="[1,2,5,10]" :page-size="getUserListParams.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>
    </el-card>
    <el-dialog title="添加用户" :visible.sync="isVisible" width="50%" @close="resetForm('add')" :close-on-click-modal="false">
      <el-form :model="addForm" :rules="addFormRules" label-width="85px" ref="addFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password">
          <el-input v-model="validPwd" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="doValidAndSendRequest">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="isEditVisible" width="50%" @close="resetForm('edit')" :close-on-click-modal="false">
      <el-form :model="editForm" :rules="addFormRules" label-width="85px" ref="editFormRef">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo(editForm.id)">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="setDistrubuteRoleVisible" title="分配角色" :close-on-click-modal="false" width="50%" @close="setRoleDialogClosed">
      <div :data="userInfo">
        <p>当前用户名：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配新角色：<el-select v-model="userNewRoleId" placeholder="选择角色" >
          <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
        </el-select></p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDistrubuteRoleVisible = false">取消</el-button>
        <el-button type="primary" @click="updateRoles">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const checkEmail = (rule, value, callback) => {
      const emailReg = /^([A-z0-9_-])+@([A-z0-9-_])+(\.[A-z0-9_-])+/i
      if(emailReg.test(value)) return callback()
      return callback(new Error('邮箱不合法，请重新输入！'))
    }
    const checkMobile = (rule, value, callback) => {
      const mobileReg = /^(0|86|17951)?(13[\d]|15[\d]|17[678]|18[\d]|14[57])[\d]{8}$/i
      if(mobileReg.test(value)) return callback()
      return callback(new Error('电话不合法，请重新输入！'))
    }

    return {
      getUserListParams: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      isVisible: false,
      isEditVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      validPwd: '',
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名在3~10个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '密码在6~15个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      setDistrubuteRoleVisible: false,
      userInfo: {},
      roleList: [],
      userNewRoleId: ''
    }
  },
  methods: {
    async getUserList() {
      const { data: response } = await this.$http.get('users', { params: this.getUserListParams })
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '获取用户列表失败！', duration: 2000 })
      this.userList = response.data.users
      this.total = response.data.total
    },
    handleSizeChange(newSize) {
      this.getUserListParams.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange(newPageNum) {
      this.getUserListParams.pagenum = newPageNum
      this.getUserList()
    },
    async userStateChange(userInfo) {
      const { data: response } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
      if(response.meta.status !== 200) {
        userInfo.mg_state = !userInfo.mg_state
        return this.$message({ type: 'error', message: '修改失败！', duration: 2000 })
      }
      return this.$message({ type: 'success', message: '修改成功!', duration: 2000 })
    },
    resetForm(type) {
      if(type === 'add') {
        return this.$refs.addFormRef.resetFields()
      }
      if(type === 'edit') {
        return this.$refs.editFormRef.resetFields()
      }
    },
    doValidAndSendRequest() {
      if(this.validPwd !== this.addForm.password) {
        return this.$message({ type: 'error', message: '前后密码不一致，请正确填写再尝试确认提交！' })
      }
      this.$refs.addFormRef.validate(async valid => {
        if(!valid) {
          return this.$message({ type: 'error', message: '请根据提示填写正确的内容在尝试确认提交！' })
        }
        const { data: response } = await this.$http.post('users', this.addForm)
        console.log(response)
        if(response.meta.status !== 201) return this.$message({ type: 'error', message: '用户添加失败！' })
        this.isVisible = false
        this.getUserList()
        this.$message({ type: 'success', message: '用户添加成功！' })
      })
    },
    showEditDialog(userInfo) {
      this.isEditVisible = true
      this.editForm.id = userInfo.id
      this.editForm.username = userInfo.username
      this.editForm.email = userInfo.email
      this.editForm.mobile = userInfo.mobile
    },
    editUserInfo(id) {
      console.log(id)
      this.$refs.editFormRef.validate(async valid => {
        if(!valid) {
          return this.$message({ type: 'error', message: '请根据提示填写正确的内容在尝试确认提交！' })
        }
        const { data: response } = await this.$http.put('users/' + id, { email: this.editForm.email, mobile: this.editForm.mobile })
        if(response.meta.status !== 200) return this.$message({ type: 'error', message: '修改用户失败！' })
        this.isEditVisible = false
        this.$message({ type: 'success', message: '修改用户信息成功！' })
        this.getUserList()
      })
    },
    async removeUserById(id) {
      const flag = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if(flag !== 'confirm') return this.$message({ type: 'info', message: '已取消删除操作！', duration: 2000 })
      const { data: response } = await this.$http.delete('users/' + id)
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '删除用户失败！' })
      this.$message({ type: 'success', message: '删除用户成功！' })
      this.getUserList()
    },
    async distrubuteRoles(userInfo) {
      this.userInfo = userInfo
      this.setDistrubuteRoleVisible = true
      const { data: response } = await this.$http.get('roles')
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '获取角色列表失败', duration: 2000 })
      this.roleList = response.data
    },
    async updateRoles() {
      if(!this.userNewRoleId) {
        this.setDistrubuteRoleVisible = false
        return
      }
      console.log(this.userInfo.id, this.userNewRoleId)
      const { data: response } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.userNewRoleId })
      if(response.meta.status !== 200) return this.$message({ type: 'error', message: '分配角色失败', duration: 2000 })
      this.$message({ type: 'success', message: '分配角色成功', duration: 2000 })
      this.getUserList()
      this.setDistrubuteRoleVisible = false
    },
    setRoleDialogClosed() {
      this.userInfo = {}
      this.userNewRoleId = ''
    }
  },
  created() {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped="scoped">
  /deep/.el-input__inner{
    height: 39px;
  }
</style>
